<template>
  <div style="display: flex; flex-direction: column; justify-content: center; align-items: center; height: 100%;">
    <el-card style="width: 95%">
      <template slot="header">
        <span>个人中心</span>
      </template>
      <div style="text-align: center;">
        <el-form ref="form" :model="userInfo">
          <!--文件上传-->
          <el-upload
            ref="uploadImage"
            action=""
            class="avatar-uploader"
            :show-file-list="false"
            :http-request="uploadImg"
            :multiple="false"
            :auto-upload="false"
            :on-change="imgSaveToUrl"
            :before-upload="beforeAvatarUpload"
            accept="image/png,image/jpg,image/jpeg"
          >
            <img
              v-if="dataForm.headUrl"
              :src="dataForm.headUrl"
              class="avatar"
              alt="无"
            >
            <i
              v-else
              class="el-icon-plus avatar-uploader-icon"
            />
          </el-upload>
          <!---->
          <el-form-item
            :label-width="formLabelWidth"
            label="账号"
          >
            <el-input
              v-model="userInfo.username"
              autocomplete="off"
              placeholder="请输入账号"
            />
          </el-form-item>
          <el-form-item
            :label-width="formLabelWidth"
            label="昵称"
          >
            <el-input
              v-model="userInfo.fullName"
              autocomplete="off"
              placeholder="请输入昵称"
            />
          </el-form-item>
          <!---->
          <el-form-item
            :label-width="formLabelWidth"
            label="邮箱"
            prop="CategoryID"
          >
            <el-input
              v-model="userInfo.email"
              autocomplete="off"
              placeholder="请输入邮箱地址"
            />
          </el-form-item>
          <!---->
          <el-form-item
            :label-width="formLabelWidth"
            label="电话"
            prop="CategoryID"
          >
            <el-input
              v-model="userInfo.phoneNumber"
              autocomplete="off"
              placeholder="请输入电话号码"
            />
          </el-form-item>
          <!-- 添加按钮 -->
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>

import { formatDate } from 'element-ui'

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      background: true,
      listLoading: true,
      isLoading: false,
      formLabelWidth: '120px',
      // 文件上传的参数
      dialogImageUrl: '',
      dialogVisible: false,
      pictureFile: '',
      dataForm: { headUrl: '' },
      img: null,
      imgChanged: false,
      // 用户的数据
      password: '',
      confirmPassword: '',
      userRole: '',
      userInfo: {
        userImageURL: '',
        username: '',
        fullName: '',
        email: '',
        phoneNumber: ''
      }
    }
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    formatDate() {
      return formatDate
    },
    getUserInfo() {
      this.$store.dispatch('user/getInfo', {})
        .then((res) => {
          this.userInfo = res
          this.listLoading = false
          this.dataForm.headUrl = this.userInfo.userImageURL
        })
    },
    // 其他的函数
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG,JPEG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    imgSaveToUrl(event) {
      if (this.beforeAvatarUpload(event)) {
        var URL = null
        if (window.createObjectURL !== undefined) {
          // basic
          URL = window.createObjectURL(event.raw)
        } else if (window.URL !== undefined) {
          // mozilla(firefox)
          URL = window.URL.createObjectURL(event.raw)
        } else if (window.webkitURL !== undefined) {
          // webkit or chrome
          URL = window.webkitURL.createObjectURL(event.raw)
        }
        this.dataForm.headUrl = URL
        this.imgChanged = true
      }
    },
    // 自定义上传方法，使用上传组件的submit()后才会触发以获取文件实体
    uploadImg(param) {
      this.img = param.file
      this.imgChanged = true
    },
    async uploadFile() {
      try {
        if (this.imgChanged) {
          // 触发上传
          this.$refs.uploadImage.submit()
          // 创建 FormData
          const formData = new FormData()
          // 如果有图片，添加到 FormData 中
          if (this.img) {
            formData.append('file', this.img)
          }
          // 调用上传文件的接口
          const res = await this.$store.dispatch('product/uploadFile', formData)
          // 处理上传结果
          if (res.code === 0) {
            // 请注意，这里修改了属性名为userInfo.userImageURL
            this.userInfo.userImageURL = res.data
            this.listLoading = false
          } else {
            this.$message.error(res.msg)
          }
        }
      } catch (error) {
        // 处理上传文件时的错误
        console.error('文件上传错误:', error)
        throw error // 将错误传播出去，以便在 uploadAndSubmit 中捕获
      }
    },
    async submitForm() {
      try {
        // 提交文件
        await this.uploadFile()
        // 提交表单
        const res = await this.$store.dispatch('user/updateInfo', this.userInfo)
        // 显示消息
        this.$message.success(res.msg)
      } catch (error) {
        // 处理错误
        console.error('Error:', error)
        this.$message.error('上传或提交表单时出错')
      }
    }

  }
}

function time(time = +new Date()) {
  const date = new Date(time + 8 * 3600 * 1000)
  return date.toJSON().substr(0, 19).replace('T', ' ').replace(/-/g, '.')
}

time() // "2018.08.09 18:25:54"
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
